package com.ruibang.glass.quality.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruibang.glass.common.constants.Constants;
import com.ruibang.glass.common.constants.RedisKey;
import com.ruibang.glass.common.domain.file.FileBusiness;
import com.ruibang.glass.quality.constant.QualityErrorCode;
import com.ruibang.glass.quality.domain.req.AppearanceSizeReq;
import com.ruibang.glass.quality.entity.AppearanceSize;
import com.ruibang.glass.quality.feign.FileApi;
import com.ruibang.glass.quality.mapper.AppearanceSizeMapper;
import com.ruibang.glass.quality.service.AppearanceSizeService;
import com.ruibang.glass.quality.util.PoiUtils;
import com.teaming.cloud.framework2.autoconfigure.redis.RedisSingleService;
import com.teaming.cloud.framework2.autoconfigure.redis.RedisSingleService;
import com.teaming.cloud.framework2.common.constant.CommonConstant;
import com.teaming.cloud.framework2.common.exception.ServiceException;
import com.teaming.cloud.framework2.common.model.ResultBody;
import com.teaming.cloud.framework2.common.pojo.PageRequest;
import com.teaming.cloud.framework2.common.pojo.PageResult;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 成品外观尺寸信息 服务实现类
 * </p>
 *
 * @author wujie
 * @since 2024-03-20
 */
@Service
public class AppearanceSizeServiceImpl extends ServiceImpl<AppearanceSizeMapper, AppearanceSize> implements AppearanceSizeService {

    private static final Integer INT_ELEVEN = 11;
    private static final Integer INT_TWELVE = 12;

    private static final Integer INT_THIRTEEN = 13;

    private static final Integer INT_FOURTEEN = 14;
    private static final Integer INT_FIFTEEN = 15;
    private static final Integer INT_NINETEEN = 19;

    private static final Integer INT_TWENTY_THREE = 23;
    private static final Integer INT_TWENTY_SEVEN = 27;

    @Autowired
    private FileApi fileApi;

//    @Autowired
//    private RedisSingleService redisService;

    @Autowired
    private RedisSingleService redisService;

    @Override
    public void saveInfo(AppearanceSize appearanceSize) {
        this.save(appearanceSize);
        //更新文件对应业务Id
        if(CollectionUtils.isNotEmpty(appearanceSize.getFileIds())){
            FileBusiness fileBusiness = new FileBusiness();
            fileBusiness.setFileIds(appearanceSize.getFileIds());
            fileBusiness.setBusinessId(appearanceSize.getSizeId());
            fileApi.updateBusinessById(fileBusiness);
        }
    }

    @Override
    public void updateInfo(AppearanceSize appearanceSize) {
        //更新文件信息
        if(CollectionUtils.isNotEmpty(appearanceSize.getDeleteFileIds())){
            fileApi.deleteByFileIds(appearanceSize.getDeleteFileIds());
        }
        //新增文件
        if(CollectionUtils.isNotEmpty(appearanceSize.getFileIds())){
            FileBusiness fileBusiness = new FileBusiness();
            fileBusiness.setBusinessId(appearanceSize.getSizeId());
            fileBusiness.setFileIds(appearanceSize.getFileIds());
            fileApi.updateBusinessById(fileBusiness);
        }

        this.updateById(appearanceSize);
    }

    @Override
    public List<AppearanceSize> queryAppearanceSize(AppearanceSizeReq strengthReq) {
        final LambdaQueryWrapper<AppearanceSize> lambda = new QueryWrapper<AppearanceSize>().lambda();
        this.buildCondition(lambda,strengthReq);
        List<AppearanceSize> list = this.list(lambda);
        Map<Object, Object> userMap = redisService.hmget(RedisKey.USER_GROUP_TYPE);
        for (AppearanceSize as : list) {
            if(userMap!=null){
                as.setUserName(userMap.get(as.getUserId())==null?"":userMap.get(as.getUserId()).toString());
            }
        }
        return list;
    }

    @Override
    public AppearanceSize importAppearanceSize(MultipartFile file) {
        AppearanceSize appearanceSize = new AppearanceSize();
        if(file == null) return appearanceSize;
        String fileName = file.getOriginalFilename();
        if(com.alibaba.excel.util.StringUtils.isNotBlank(fileName)){
            int dotIndex = fileName.lastIndexOf('.');
            String suffix = fileName.substring(dotIndex + 1);
            if(com.alibaba.excel.util.StringUtils.isNotBlank(suffix)){
                if(Constants.FILE_TYPE_XLSM.equals(suffix)
                        ||Constants.FILE_TYPE_XLS.equals(suffix)
                        ||Constants.FILE_TYPE_XLSX.equals(suffix)){
                    InputStream inputStream = null;
                    Workbook workbook = null;
                    try {
                        inputStream = file.getInputStream();
                        workbook = WorkbookFactory.create(inputStream);
                        int sheetCount = workbook.getNumberOfSheets();
                        if(sheetCount >= CommonConstant.ONE_INT){
                            Sheet sheet = workbook.getSheetAt(CommonConstant.ZERO_INT);
                            Row row2 = sheet.getRow(CommonConstant.TWO_INT);
                            Cell cell1 = row2.getCell(CommonConstant.ONE_INT);
                            if(!PoiUtils.isEmptyCell(cell1)){
                                appearanceSize.setGlassModel(cell1.getStringCellValue());//玻璃型号
                            }

                            Cell cell2 = row2.getCell(CommonConstant.FIVE_INT);
                            if(!PoiUtils.isEmptyCell(cell2)) {
                                LocalDate measureDate = cell2.getLocalDateTimeCellValue().toLocalDate();
                                if(measureDate!=null){
                                    appearanceSize.setMeasureDate(measureDate);
                                }
                            }


                            Cell cell3 = row2.getCell(CommonConstant.SEVEN_INT);
                            if(!PoiUtils.isEmptyCell(cell3)) {
                                LocalDateTime dateTime = cell3.getLocalDateTimeCellValue();
                                appearanceSize.setCheckTime(dateTime.getHour()+":"+dateTime.getMinute()+":"+dateTime.getSecond());
                            }


                            Cell cell4 = row2.getCell(CommonConstant.NINE_INT);
                            if(!PoiUtils.isEmptyCell(cell4)) {
                                appearanceSize.setGlassId(cell4.getStringCellValue());
                            }

                            try {
                                Cell cell5 = row2.getCell(INT_FIFTEEN);
                                if (!PoiUtils.isEmptyCell(cell5)) {
                                    String name = cell5.getStringCellValue();
                                    if (StringUtils.isNotBlank(name)) {
                                        appearanceSize.setProductLineName(name);
                                        Map<Object, Object> productMap = redisService.hmget(RedisKey.PRODUCT_LINE_GROUP_TYPE);
                                        if (productMap != null) {
                                            Map<String, String> productNameMap = new HashMap<>();
                                            productMap.forEach((k, v) -> {
                                                if (v != null && com.alibaba.excel.util.StringUtils.isNotBlank(v.toString())) {
                                                    productNameMap.put(v.toString(), k.toString());
                                                }
                                            });
                                            appearanceSize.setProductLine(productNameMap.get(name));
                                        }
                                    }
                                }

                            } catch (Exception e) {
                                throw new ServiceException(QualityErrorCode.WRITE_PRODUCTION_LINE.getCode(), QualityErrorCode.WRITE_PRODUCTION_LINE.getMsg());
                            }


                            Cell cell6 = row2.getCell(INT_NINETEEN);
                            if(!PoiUtils.isEmptyCell(cell6)) {
                                String userName = cell6.getStringCellValue();
                                if(com.alibaba.excel.util.StringUtils.isNotBlank(userName)){
                                    Map<Object, Object> userMap = redisService.hmget(RedisKey.USER_GROUP_TYPE);
                                    if(!userMap.isEmpty()){
                                        Map<String,String> userNameMap = new HashMap<>();
                                        userMap.forEach((k,v)->{
                                            if(v!=null&& com.alibaba.excel.util.StringUtils.isNotBlank(v.toString())){
                                                userNameMap.put(v.toString(),k.toString());
                                            }
                                        });
                                        appearanceSize.setUserId(userNameMap.get(userName));
                                    }
                                }
                            }

                            Row row11 = sheet.getRow(INT_NINETEEN);
                            Cell cell7 = row11.getCell(CommonConstant.ONE_INT);
                            if(!PoiUtils.isEmptyCell(cell7)) {
                                appearanceSize.setSize2h((float)cell7.getNumericCellValue());
                            }

                            Cell cell8 = row11.getCell(CommonConstant.TWO_INT);
                            if(!PoiUtils.isEmptyCell(cell8)) {
                                appearanceSize.setSize4h((float)cell8.getNumericCellValue());
                            }

                            Cell cell9 = row11.getCell(CommonConstant.THREE_INT);
                            if(!PoiUtils.isEmptyCell(cell9)) {
                                appearanceSize.setSize1h((float)cell9.getNumericCellValue());
                            }

                            Cell cell10 = row11.getCell(CommonConstant.FOUR_INT);
                            if(!PoiUtils.isEmptyCell(cell10)) {
                                appearanceSize.setSize3h((float)cell10.getNumericCellValue());
                            }

                            Row row27 = sheet.getRow(INT_TWENTY_SEVEN);
                            Cell cell11 = row27.getCell(CommonConstant.ONE_INT);
                            if(!PoiUtils.isEmptyCell(cell11)) {
                                appearanceSize.setVertical1c((float)cell11.getNumericCellValue());
                            }

                            Cell cell12 = row27.getCell(CommonConstant.TWO_INT);
                            if(!PoiUtils.isEmptyCell(cell12)) {
                                appearanceSize.setVertical2c((float)cell12.getNumericCellValue());
                            }

                            Cell cell13 = row27.getCell(CommonConstant.THREE_INT);
                            if(!PoiUtils.isEmptyCell(cell13)) {
                                appearanceSize.setVertical3c((float)cell13.getNumericCellValue());
                            }

                            Cell cell14 = row27.getCell(CommonConstant.FOUR_INT);
                            if(!PoiUtils.isEmptyCell(cell14)) {
                                appearanceSize.setVertical4c((float)cell14.getNumericCellValue());
                            }

                            Cell cell15 = row27.getCell(CommonConstant.FIVE_INT);
                            if(!PoiUtils.isEmptyCell(cell15)) {
                                appearanceSize.setParallel2h4h((float)cell15.getNumericCellValue());
                            }

                            Cell cell16 = row27.getCell(CommonConstant.SIX_INT);
                            if(!PoiUtils.isEmptyCell(cell16)) {
                                appearanceSize.setParallel1h3h((float)cell16.getNumericCellValue());
                            }

                            Cell cell17 = row27.getCell(CommonConstant.SEVEN_INT);
                            if(!PoiUtils.isEmptyCell(cell17)) {
                                appearanceSize.setRightAngle1c((float)cell17.getNumericCellValue());
                            }

                            Cell cell18 = row27.getCell(CommonConstant.EIGHT_INT);
                            if(!PoiUtils.isEmptyCell(cell18)) {
                                appearanceSize.setRightAngle2c((float)cell18.getNumericCellValue());
                            }

                            Cell cell19 = row27.getCell(CommonConstant.NINE_INT);
                            if(!PoiUtils.isEmptyCell(cell19)) {
                                appearanceSize.setRightAngle3c((float)cell19.getNumericCellValue());
                            }

                            Cell cell20 = row27.getCell(CommonConstant.TEN_INT);
                            if(!PoiUtils.isEmptyCell(cell20)) {
                                appearanceSize.setRightAngle4c((float)cell20.getNumericCellValue());
                            }

                            Cell cell21 = row27.getCell(INT_ELEVEN);
                            if(!PoiUtils.isEmptyCell(cell21)) {
                                appearanceSize.setStraightLine1h((float)cell21.getNumericCellValue());
                            }

                            Cell cell22 = row27.getCell(INT_TWELVE);
                            if(!PoiUtils.isEmptyCell(cell22)) {
                                appearanceSize.setStraightLine2h((float)cell22.getNumericCellValue());
                            }

                            Cell cell23 = row27.getCell(INT_THIRTEEN);
                            if(!PoiUtils.isEmptyCell(cell23)) {
                                appearanceSize.setStraightLine3h((float)cell23.getNumericCellValue());
                            }

                            Cell cell24 = row27.getCell(INT_FOURTEEN);
                            if(!PoiUtils.isEmptyCell(cell24)) {
                                appearanceSize.setStraightLine4h((float)cell24.getNumericCellValue());
                            }

                            Row row23 = sheet.getRow(INT_TWENTY_THREE);
                            Cell cell25 = row23.getCell(CommonConstant.ONE_INT);
                            if(!PoiUtils.isEmptyCell(cell25)) {
                                appearanceSize.setChamfer1c1((float)cell25.getNumericCellValue());
                            }

                            Cell cell26 = row23.getCell(CommonConstant.TWO_INT);
                            if(!PoiUtils.isEmptyCell(cell26)) {
                                appearanceSize.setChamfer1c2((float)cell26.getNumericCellValue());
                            }

                            Cell cell27 = row23.getCell(CommonConstant.THREE_INT);
                            if(!PoiUtils.isEmptyCell(cell27)) {
                                appearanceSize.setChamfer2c1((float)cell27.getNumericCellValue());
                            }

                            Cell cell28 = row23.getCell(CommonConstant.FOUR_INT);
                            if(!PoiUtils.isEmptyCell(cell28)) {
                                appearanceSize.setChamfer2c2((float)cell28.getNumericCellValue());
                            }

                            Cell cell29 = row23.getCell(CommonConstant.FIVE_INT);
                            if(!PoiUtils.isEmptyCell(cell29)) {
                                appearanceSize.setChamfer4c1((float)cell29.getNumericCellValue());
                            }

                            Cell cell30 = row23.getCell(CommonConstant.SIX_INT);
                            if(!PoiUtils.isEmptyCell(cell30)) {
                                appearanceSize.setChamfer4c2((float)cell30.getNumericCellValue());
                            }

                            Cell cell31 = row23.getCell(CommonConstant.SEVEN_INT);
                            if(!PoiUtils.isEmptyCell(cell31)) {
                                appearanceSize.setChamfer3c1((float)cell31.getNumericCellValue());
                            }

                            Cell cell32 = row23.getCell(CommonConstant.EIGHT_INT);
                            if(!PoiUtils.isEmptyCell(cell32)) {
                                appearanceSize.setChamfer3c2((float)cell32.getNumericCellValue());
                            }

                        }

                    } catch (IOException e) {
                        log.error("执行流操作异常:"+e.getMessage());
                        throw new ServiceException(QualityErrorCode.SEMI_IMPORT_FILE_ERROR.getCode(),QualityErrorCode.SEMI_IMPORT_FILE_ERROR.getMsg());
                    }finally {
                        try {
                            if(inputStream!=null){
                                inputStream.close();
                            }
                            if(workbook!=null){
                                workbook.close();
                            }
                        } catch (IOException e) {
                            log.error("流关闭异常:"+e.getMessage());
                        }
                    }
                }
            }
        }

        ResultBody<String> resultBody = fileApi.uploadFile(file);
        if(resultBody!=null&& com.alibaba.excel.util.StringUtils.isNotBlank(resultBody.getData())){
            appearanceSize.setFileIds(Arrays.asList(resultBody.getData()));
        }

        return appearanceSize;
    }

    @Override
    public void delete(String id) {
        lambdaUpdate().eq(AppearanceSize::getSizeId, id).set(AppearanceSize::getIsDelete, CommonConstant.ONE_STR).update();
    }
    @Override
    public PageResult<AppearanceSize> queryPage(PageRequest<AppearanceSizeReq> pageRequest) {
        final AppearanceSizeReq param = pageRequest.getParam();
        final LambdaQueryWrapper<AppearanceSize> lambda = new QueryWrapper<AppearanceSize>().lambda();
        this.buildCondition(lambda,param);
        final IPage<AppearanceSize> page = this.page(new Page<>(pageRequest.getPageNo(), pageRequest.getPageSize()), lambda);
        if(page!=null&& CollectionUtils.isNotEmpty(page.getRecords())){
            List<String> ids = page.getRecords().stream().map(c->c.getSizeId()).collect(Collectors.toList());
            ResultBody<List<FileBusiness>> resultBody = fileApi.getFileBusinessByIds(ids);
            Map<String,List<String>> fileMap = null;
            if(resultBody!=null&& com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isNotEmpty(resultBody.getData())){
                fileMap = resultBody.getData().stream().collect(Collectors.toMap(f->f.getBusinessId(), f->f.getFileIds(),(f1, f2)->f1));
            }

            Map<Object, Object> userMap = redisService.hmget(RedisKey.USER_GROUP_TYPE);

            for (AppearanceSize record : page.getRecords()) {
                if(fileMap!=null){
                    record.setFileIds(fileMap.get(record.getSizeId()));
                }

                if(userMap!=null){
                    record.setUserName(userMap.get(record.getUserId())==null?"":userMap.get(record.getUserId()).toString());
                }
            }
        }

        PageResult<AppearanceSize> pr = new PageResult(page);
        return pr;
    }

    /**
     * 构造查询条件
     * @param lambda
     * @param param
     */
    private void buildCondition(LambdaQueryWrapper<AppearanceSize> lambda, AppearanceSizeReq param){
        lambda.eq(AppearanceSize::getIsDelete, CommonConstant.ZERO_STR);
        if(null == param) return;
        if(StringUtils.isNotBlank(param.getSizeId())){
            lambda.eq(AppearanceSize::getSizeId, param.getSizeId());
        }
        if(StringUtils.isNotBlank(param.getGlassId())){
            lambda.eq(AppearanceSize::getGlassId, param.getGlassId());
        }
        if(StringUtils.isNotBlank(param.getGlassModel())){
            lambda.eq(AppearanceSize::getGlassModel, param.getGlassModel());
        }
        if(param.getMeasureStartDate()!=null&&param.getMeasureEndDate()!=null){
            lambda.ge(AppearanceSize::getMeasureDate, param.getMeasureStartDate());
            lambda.le(AppearanceSize::getMeasureDate, param.getMeasureEndDate());
        }
        if(StringUtils.isNotBlank(param.getCheckTime())){
            lambda.eq(AppearanceSize::getCheckTime, param.getCheckTime());
        }
        if(StringUtils.isNotBlank(param.getProductLine())){
            lambda.eq(AppearanceSize::getProductLine, param.getProductLine());
        }
        if(StringUtils.isNotBlank(param.getUserId())){
            lambda.eq(AppearanceSize::getUserId, param.getUserId());
        }
        if(StringUtils.isNotBlank(param.getDecide())){
            lambda.eq(AppearanceSize::getDecide, param.getDecide());
        }
        lambda.orderBy(true,false, AppearanceSize::getMeasureDate);
    }
}
